<template>
    <div style="position: absolute;width:260px;height:30px;top:86px;left: calc(100vw - 260px);z-index: 999">
        <el-dropdown style="display: inline" >
            <el-link style="float: left;line-height: 30px;margin-right: 5px;" type="success">排队数量: {{queueInfo.allNum}}</el-link>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item v-for="chatType in queueInfo.chatTypes">{{chatType.typeName}} : {{chatType.waitingNum}}</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
        <el-button-group  style="display: inline" >
            <el-button type="primary" v-if="!state.signIn" @click="signIn">签入</el-button>
            <el-button type="primary" v-if="state.signIn" @click="signOut">签出</el-button>
            <el-button type="primary" @click="ready" :disabled="!state.ready">就绪</el-button>
            <el-button type="primary" @click="rest" :disabled="!state.rest">小休</el-button>
        </el-button-group>
    </div>
    <el-row>
        <el-col :span="24">
            <el-tabs type="border-card" closable @tab-remove="tabRemove" @tab-click="tabClick" v-model="currentChat.clientName" class="demo-tabs">
                <el-tab-pane v-for="chat in chats" :key="chat.id" :name="chat.clientName" >
                    <template #label>
                        <span class="custom-tabs-label">
                                <span>
                                    {{chat.clientName}}
                                </span>
                              <el-badge v-if="chat.unreadCount > 0" class="mark" style="margin-left:5px" :value="chat.unreadCount" />
                        </span>
                    </template>
                    <el-row>
                    <el-col :span="12">
                    <div>
                        <!--消息框-->
                        <div class ="scrollDiv" ref="msgBoxs" :title="chat.id" style="height:calc(100vh - 340px); overflow:auto; border: 1px solid #ccc;
                        border-radius: 5px;background-color: #f5f5f5;">
                            <Messages :msgs="chat.msgs" showAt="agent"/>
                        </div>
                            <!--消息框结束-->
                            <div style="display: flex;height:20px;border:none;margin: 0 15px">
                                <div>
                                <el-upload
                                        ref="uploadRef"
                                        class="upload-demo"
                                        action="/api/common/upload/imgMsg"
                                        :show-file-list="false"
                                        :before-upload="beforeUpload"
                                        :on-success = onSuccess
                                        :on-error = onError
                                >
                                    <template #trigger>
                                        <el-tooltip
                                                class="box-item"
                                                effect="light"
                                                content="发送图片"
                                                placement="top"
                                        >
                                            <el-icon title=""><Picture /></el-icon>
                                        </el-tooltip>
                                    </template>
                                </el-upload>
                                </div>
                                <div>
                                    <el-tooltip
                                            class="box-item"
                                            effect="light"
                                            :content="audioTitle"
                                            placement="top"
                                    >
                                        <el-icon style="margin: 0 15px" @mousedown="startRecordAudio" @mouseup="endRecordAudio"><Microphone /></el-icon>
                                    </el-tooltip>
                                </div>
                            </div>
                        <!--输入框-->
                        <div style="height: 120px;border-radius: 5px;border:1px solid #ccc;" v-show ="chat.alive">
                            <textarea @keydown.enter.prevent="send(chat)" style="height: 100%; width: 100%; padding-top: 10px;
                             outline: none;border: none; resize: none" v-model="chat.inputBox" />
                            <el-button style="margin-top:10px;float:right" type="primary"  @click="send(chat)">发送</el-button>
                        </div><!--输入框结束-->
                    </div>
                    </el-col>
                    <el-col :span="12" style="padding:0 5px">
                        <el-tabs  style="height: 100%" type="border-card" >
                            <el-tab-pane label="服务单"><ServiceTicket :chatId="chat.id" :clientId="chat.clientId" type="edit"/></el-tab-pane>
                            <el-tab-pane label="历史记录" class="scrollDiv" style="height:calc(100vh - 240px);overflow-y: scroll" ><Chat :clientId="chat.clientId" /></el-tab-pane>
                        </el-tabs>
                    </el-col>
                    </el-row>
                </el-tab-pane>
            </el-tabs>
        </el-col>
    </el-row>
    <el-dialog
            v-model="closeConfirm"
            title="确认"
            width="30%"
    >
        <span>确认关闭和{{currentChat.clientName}}的会话?</span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeConfirm = false">取消</el-button>
            <el-button type="primary" @click="closeChat">
              确认
            </el-button>
          </span>
        </template>
    </el-dialog>
    <RecordAudio ref="recordAudio"/>
</template>

<script setup>
    import {ElMessage} from 'element-plus'
    import {nextTick, onMounted, reactive, ref,onUnmounted} from 'vue'
    import ServiceTicket from '@/components/business/ServiceTicket.vue'
    import Messages from '@/components/common/Messages.vue'
    import RecordAudio from '@/components/business/RecordAudio.vue'
    import Chat from '@/views/business/Chat.vue'
    import moment from 'moment'
    import {Picture,Microphone} from '@element-plus/icons-vue'
    import request from '@/utils/request.js'
    import Recorder from 'js-audio-recorder';

    let currentChat = reactive({clientName:null})
    const msgBoxs = ref([])
    let chats = reactive([])
    let keepalive = null
    let websocket = null
    let msgMap = new Map()
    let agentId = null
    let connect = false
    let closeConfirm = ref(false)
    let recordAudio = ref(null)
    let waitForClose = null
    let queueInfo = reactive({allNum:0, chatTypes:[]})
    let state = reactive({signIn:false, ready:false, rest:false})
    let recorder = null
    let audioTitle = ref('发送语音')
    onMounted(function () {
        recorder = new Recorder({ sampleBits: 16 ,
            // 采样位数，支持 8 或 16，默认是16 sampleRate: 16000 ,
            // 采样率，支持 11025、16000、22050、24000、44100、48000，
            // 根据浏览器默认值，我的chrome是48000
            numChannels: 1,// 声道，支持 1 或 2， 默认是1 //
            compiling: false,
        })
        //(0.x版本中生效,1.x增加中) // 是否边录边转换，默认是false

        let userdb = JSON.parse(sessionStorage.getItem("user")||"{}")
        agentId = userdb.id
        let host = window.location.host
        websocket  = new WebSocket(`ws://${host}/socket/agent/` + userdb.id + "/0")

        websocket.onerror = function (e) {
            ElMessage({message: "websocket连接出错", type: 'error'})
        }
        websocket.onopen = function(){
            connect = true
        }
        websocket.onmessage = function (event) {
            console.log(event.data)
            let msg = JSON.parse(event.data);

            if("queue" == msg.type){
                let queueInfos = JSON.parse(msg.content)
                makeQueueInfo(queueInfos)
                return
            }

            let chat = null
            let index = null
            for(let i=0; i < chats.length; i++){
                if(chats[i].id == msg.chatId){
                    chat = chats[i]
                    index = i
                    break
                }
            }
            if("close" == msg.type && "agent" == msg.sender){
                chats.splice(index)
                closeConfirm.value = false
                return
            }
            if("close" == msg.type && "client" == msg.sender){
                chat.alive = false
                return
            }
            if(chat == null){
                chat = {
                    id : msg.chatId,
                    clientName : msg.senderName,
                    clientId : msg.senderId,
                    unreadCount : 1,
                    alive : true,
                    msgs:[msg]
                }
                chats.push(chat)
            }else{
                chat.msgs.push(msg)
                if(msg.sender != "agent"){
                    if(currentChat.id != chat.id){
                        chat.unreadCount++
                    }
                }
            }
            if(currentChat.clientName == null || currentChat.clientName == msg.senderName){// 消息来自当前聊天的客户
                for(let key in chat){
                    currentChat[key] = chat[key]
                }
            }

            if('client' === msg.sender){
                if(chats.length == 1){
                    currentChat.clientName = msg.senderName
                    chat.unreadCount = 0
                }
            }
            scrollerToBottom(chat.id)
        }
        keepalive = setInterval(function(){
            // request.get(`/api/keepalive`)
            // let msg = {"type" : "keepalive"}
            // websocket.send(JSON.stringify(msg))
            },
          30*1000)
    })
    onUnmounted(function () {
        websocket.close()
        clearInterval(keepalive)
    })

    function send(chat){

        let content = chat.inputBox.trim()
        if(content===""){
            ElMessage({message: "请输入内容",type: 'error'})
            return
        }
        let msg = {"content" : content, "type" : "text","chatId" : chat.id, "senderName" : currentChat.senderName}
        websocket.send(JSON.stringify(msg))
        chat.inputBox = ""
    }

    function tabRemove(clientName){
        closeConfirm.value = true
        for(let i=0; i < chats.length; i++){
            if(chats[i].clientName == clientName){
                waitForClose = chats[i]
                break
            }
        }
    }

    function closeChat() {
        let msg = {"type" : "close", "chatId" : waitForClose.id, "senderName" : waitForClose.senderName}
        websocket.send(JSON.stringify(msg))
    }
    function tabClick(tab, event){
        let chat = null
        currentChat.clientName = tab.props.name
        for(let i=0; i < chats.length; i++){
            if(chats[i].clientName == tab.props.name){
                chat = chats[i]
                currentChat = chat
                break
            }
        }
        chat.unreadCount = 0
    }

    function scrollerToBottom(chatId) {
        let areas = msgBoxs.value
        let thisArea = null
        for (let i=0;i<areas.length;i++){
            let temp = areas[i]
            if(temp.title == chatId){
                thisArea = temp
                break
            }
        }
        nextTick(() => {
            if(thisArea !== null){
                thisArea.scrollTop = thisArea.scrollHeight
            }

        });
    }

    function makeQueueInfo(queueInfos) {
        let allNum = 0
        queueInfo.chatTypes = []
        queueInfos.forEach(info =>{
            queueInfo.chatTypes.push({"typeName" : info.typeName, "waitingNum" : info.waitingNum})
            allNum = allNum + info.waitingNum
        })
        queueInfo.allNum = allNum
    }

    function signIn(){
        if(!connect){
            ElMessage({message: "请等待连接成功",type: 'error'})
        }
        request.get(`/api/online/signIn/${agentId}`).then(resp => {
            state.signIn = true
           state.ready = true
           state.rest = false
        })
    }
    function signOut(){
        if(!connect){
            ElMessage({message: "请等待连接成功",type: 'error'})
        }
        request.get(`/api/online/signOut/${agentId}`).then(resp => {
            state.ready = false
            state.rest = false
            state.signIn = false
        })
    }
    function ready(){
        if(!connect){
            ElMessage({message: "请等待连接成功",type: 'error'})
        }
        request.get(`/api/online/ready/${agentId}`).then(resp => {
            state.ready = false
            state.rest = true
        })
    }
    function rest(){
        if(!connect){
            ElMessage({message: "请等待连接成功",type: 'error'})
        }
        request.get(`/api/online/rest/${agentId}`).then(resp => {
            state.ready = true
            state.rest = false
        })
    }

    const beforeUpload = (rawFile) => {
        console.log("文件格式："+rawFile.type)
        if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
            ElMessage.error('必须是 JPG或PNG 格式!')
            return false
        } else if (rawFile.size / 1024 / 1024 > 2) {
            ElMessage.error('文件大小不能大于2MB!')
            return false
        }
        return true
    }
    function onSuccess(response, uploadFile, uploadFiles,chat){
        ElMessage.success('发送图片成功!')
        let msg = {"content" : response.data, "type" : "image","chatId" : currentChat.id, "senderName" : currentChat.senderName}
        let realMsg = JSON.stringify(msg)
        websocket.send(realMsg)
    }
    function onError(error, uploadFile, uploadFiles){
        ElMessage.error('发送图片失败' + error)
    }
    function startRecordAudio(){
        ElMessage({message: '开始录音',type: 'success',duration:700,})
        audioTitle.value ='正在录制。。。'
        Recorder.getPermission().then(() => {
            recorder.start(); // 开始录音
        },(error) => {
            ElMessage({message: '请先允许该网页使用麦克风',type: 'error',duration:700,})
        });
    }
    function endRecordAudio(){
        ElMessage({message: '录音结束',type: 'success',duration:700,})
        audioTitle.value = '发送语音';
        recorder.stop(); // 结束录音
        let wavBlob = recorder.getWAVBlob();
        let formData = new FormData()
        const newbolb = new Blob([wavBlob], { type: 'audio/wav' })
        const fileOfBlob = new File([newbolb], new Date().getTime() + '.wav')
        formData.append('file', fileOfBlob)
        const config= {
            headers: { "Content-Type": "multipart/form-data;boundary="+new Date().getTime() }
        };
        request.post("/api/common/upload/audio", formData, config).then(resp => {
            let msg = {"content" : resp, "type" : "audio", "chatId" : currentChat.id, "senderName" : currentChat.senderName}
            let realMsg = JSON.stringify(msg)
            websocket.send(realMsg)
        })
    }
</script>
<style lang="css">
    .tip {
        border-radius: 10px;
        padding: 10px;
        width:auto;
        display:inline-block;
        word-wrap: break-word;
        word-break: break-all;
        text-align:left;
        max-width:60%;
    }
    .time {
        padding: 5px;
        display:inline-block;
        color: #8f9093;
        font-size: 13px;
    }
    .item {
        margin-top: 5px;
    }
    .right {
        background-color: #84db49;
    }
    .left {
        background-color:  white;
    }
    .span-box {
        display: flex;
        justify-content: flex-start;
        align-items: center;}
    .btn-bell-badge {
        width: 26px;
        height: 18px;
        margin-left:5px;
        line-height:18px;
        border-radius: 15px;
        background: #f56c6c;}
    .num {
        display: block;
        width: 100%;
        text-align: center;
        font-size: 12px;
        color: #fff;
    }
</style>